package com.beiding.dbrequest.common;

import java.util.concurrent.*;

/**
 * 执行者线程池
 * @author 丁常磊
 * @date 2021/7/28 15:32
 */

public class ExecutorPool {

    private static ExecutorService[] executorServices;

    static {
        executorServices = new ExecutorService[Common.availableProcessors()];
        for (int i = 0; i < executorServices.length; i++) {
            int fi = i;
            executorServices[i] =
                    new ThreadPoolExecutor(1, 1,
                            0L, TimeUnit.MILLISECONDS,
                            new LinkedBlockingQueue<>(), r -> {
                        Thread thread = new Thread(r);
                        thread.setName("单线程执行线程-" + fi);
                        return thread;
                    });
        }
    }

    /**
     * 轮询获取一个线程
     * @return
     */
    public static ExecutorService getOne() {
        ThreadLocalRandom threadLocalRandom = ThreadLocalRandom.current();
        return executorServices[threadLocalRandom.nextInt(executorServices.length)];
    }

}
